package ch02.test01;

import java.io.*;

/**
 * @author lwj
 * @date 2025-03-10
 * @vesion 1.0.0
 */
public class CopyThread extends Thread{
    /**
     * 拷贝原文件
     */
    private String source;
    /**
     * 拷贝的目标文件
     */
    private String target;
    /**
     * 拷贝文件的状态
     */
    private FileData fileData;

    // 构造方法
    public CopyThread() {}
    public CopyThread(String source, String target, FileData fileData) {
        this.source = source;
        this.target = target;
        this.fileData = fileData;
    }

    @Override
    public void run() {
        // 获取源文件对象
        File sourceFile = new File(source);

        // 获取目标文件对象
        File targetFile = new File(target);

        // 获取源文件对象的总容量
        long totalSize = sourceFile.length();
        this.fileData.setTotalSize(totalSize);

        try(
            FileInputStream fileInputStream = new FileInputStream(sourceFile);
            FileOutputStream fileOutPutStream = new FileOutputStream(targetFile);
        ){
            byte[] buffer = new byte[1024];
            int size = 0;
            while((size = fileInputStream.read(buffer)) != -1){
                fileOutPutStream.write(buffer,0,size);

                this.fileData.setCopiedSize(size);
            }
            System.out.println("完成进度: 100%");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
